<template>
  <div class="header">
    <a-form
      ref="formRefState"
      :model="formState"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 20 }"
      name="normal_login"
      class="login-form"
    >
      <a-form-item label="类型" name="type">
        <a-select
          v-model:value="formState.type"
          placeholder="请选择类型"
          :field-names="{ label: 'text', value: 'value' }"
          :options="options2"
        ></a-select>
      </a-form-item>

      <a-form-item label="上传截图" name="imageList">
        <a-upload
          v-model:fileList="fileList"
          list-type="picture-card"
          :capture="undefined"
          :maxCount="5"
          name="file"
          :multiple="true"
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          :before-upload="beforeUpload"
          :custom-request="ChanUpLoad"
          @remove="deleteButton"
          @preview="handlePreview"
          @change="onChange"
        >
          <div v-if="fileList.length < 5">
            <plus-outlined />
            <div style="margin-top: 8px">上传</div>
          </div>
        </a-upload>
      </a-form-item>

      <a-form-item label="上传说明" name="description">
        <a-textarea
          v-model:value="formState.description"
          placeholder="请输入说明"
          show-count
          :rows="4"
          :maxlength="100"
        />
      </a-form-item>
    </a-form>

    <a-modal
      v-model:open="previewVisible"
      centered
      :footer="null"
      :confirmLoading="confirmLoading"
      @cancel="previewVisible = false"
    >
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { InboxOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { getIsHint } from '@/utils/validate'
import { getUploadToAliOss, getAddAudit } from '@/api/black'
import Config from '@/settings'

const fileList = ref([]) as any // 图片链接回显

const TuList = ref([]) as any
const formRefState = ref() // 表单实例

const previewVisible = ref(false) // 放大的对话框
const confirmLoading = ref(false) // 确定按钮的加载状态

const userInfo = ref({}) // 用户信息

const emit = defineEmits(['refreshTu'])

const formState = ref({
  imageList: [] as any, // 上传截图
  type: null, // 类型
  description: '', // 说明
})

const validKey = () => {
  if (formState.value.imageList.length == 0) {
    return Promise.reject(new Error('请上传截图'))
  } else {
    return Promise.resolve()
  }
}

const rules: Record<string, Rule[]> = {
  imageList: [{ required: true, validator: validKey, trigger: 'blur' }],
  description: [{ required: true, message: '请输入说明', trigger: 'blur' }],
  type: [{ required: true, message: '请选择分类', trigger: 'change' }],
}

const options2 = Config.data.blackType

// 上传文件前的回调
const beforeUpload = (file: any) => {
  // console.log(file, 111);
  while (file.type.indexOf('image/jpeg') === -1 && file.type.indexOf('image/png') === -1) {
    getIsHint('error', '只能上传 jpeg 和 png 的 图片哦~')

    return false
  }

  return file
}

const onChange = (file: any) => {
  const a = file.file
  while (a.type.indexOf('image/jpeg') === -1 && a.type.indexOf('image/png') === -1) {
    fileList.value.find((item: any) => {
      if (item.uid === a.uid) {
        item.status = 'error'
      }
    })

    return
  }
}

const ChanUpLoad = async (file: any) => {
  // 原图名称
  const fileName = file.file.name
  // 图片类型
  const type = fileName.substring(fileName.lastIndexOf('.') + 1)
  // 文件
  const newImg = `${new Date().getTime() + Math.floor(Math.random() * 150)}.${type}`

  const formData = new FormData()
  formData.append('file', file.file)

  const files = file.file

  const res = await getUploadToAliOss({
    file: files,
    type: '99', // 其他图片
  })

  const imageList = res.data

  switch (res.state) {
    case 200:
      previewImage.value = imageList

      TuList.value.push({
        uid: files.uid,
        name: newImg,
        status: 'done',
        url: imageList,
        thumbUrl: imageList,
      })

      fileList.value = TuList.value

      formState.value.imageList.push(imageList)

      getIsHint('success', '图片上传成功~')
      break
    default:
      getIsHint('error', '图片上传失败~')
      break
  }
}

const previewImage: any = ref() // 放大显示

// 点击放大
const handlePreview = async (file: any) => {
  previewImage.value = file.url
  previewVisible.value = true
}

// 点击删除
const deleteButton = (file: any) => {
  fileList.value.forEach((item: any, index: any) => {
    if (item.uid == file.uid) {
      fileList.value.splice(index, 1)

      const a = formState.value.imageList.findIndex((value: any) => value == item.url)
      formState.value.imageList.splice(a, 1)

      // emit('refreshTu', item.url, '删');
    }
  })

  TuList.value = fileList.value
}

// 重置
const onMoFailed = (val: any) => {
  userInfo.value = val

  formState.value = {
    imageList: [] as any, // 上传截图
    type: null, // 类型
    description: '', // 说明
  }

  TuList.value = []
  fileList.value = []
  previewImage.value = ''
}

// 点击确定
const onOk = async () => {
  formRefState.value.validate().then(async (values: any) => {
    confirmLoading.value = true
    try {
      const { data, state, message } = await getAddAudit({
        ...formState.value,
        fansId: userInfo.value.id,
      })

      if (state === 200) {
        getIsHint('success', '提交成功~')
        confirmLoading.value = false

        emit('refreshTu')
      } else {
        getIsHint('error', message)
        confirmLoading.value = false
      }
    } catch (err) {
      getIsHint('error', '提交失败~')
      confirmLoading.value = false
    }
  })
}

defineExpose({
  onMoFailed,
  onOk,
})
</script>
<style lang="less" scoped>
.header {
  margin-top: 20px;
  width: 100%;
}
</style>
